<?php
session_start();

if(empty($_SESSION['user'])){
    echo "请先登录";
    $url='/index.php';
    echo "<a href='".$url."'>".'返回首页'."</a>";
    die();
}else if($_SESSION['usertype']!='admin'){

    echo "您没有管理员权限";
    $url='/index.php';
    echo "<a href='".$url."'>".'返回首页'."</a>";
    die();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<a href="index.php">返回首页</a><br>
<?php


try {
    include "functions.php";
    if(hasBook($_POST['bookid'])){
        echo "该书已经存在";
        $url='/addBook.php';
        echo "<a href='".$url."'>".'重新添加书籍'."</a>";
        die();
    }

    if(!isset($_FILES['image'])){
        die('无文件上传');
    }
    if($_FILES['image']['error']!=0){
        print_r('$_FILES[\'image\'][\'error\']');
        die('文件上传错误');
    }
    $allow=[
        'image/jpeg',
        'image/png',
        'image/gif',
        'image/bmp'
    ];
    if(!in_array($_FILES['image']['type'],$allow)){
        die("禁止上传该类型文件");
    }

    $file_name=$_FILES['image']['name'];
    $file_name=explode('.',$file_name)[1];
    $file_name=md5_file($_FILES['image']['tmp_name']).time().'.'.$file_name;
    $file_name='upload/'.$file_name;
    move_uploaded_file($_FILES['image']['tmp_name'],$file_name);

    $db =connectDB();
    $statement=$db->prepare('insert into Book(ID,Name,Author,Intro,Status,BookImg) VALUES (:id,:name,:author,:intro,1,:bookimg)');


    $data[':id']=$_POST['bookid'];
    $data[':name']=$_POST['bookname'];
    $data[':author']=$_POST['author'];
    $data[':intro']=$_POST['intro'];
    $data['bookimg']=$file_name;
    if($statement->execute($data)){
        echo "<h3>添加成功！</h3>";

        echo "<a href='/book.php?id=".$_POST['bookid']."'>查看</a>";
    }else{
        echo "<h3>添加失败！</h3>";
        $url='/index.php';
        echo "<a href='".$url."'>".'返回首页'."</a>";
    }


} catch (PDOException $e) {
    var_dump($e->getMessage());
    die('程序出错');
}
?>


</body>
</html>